package entry78;

import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.util.Date;

public class Period implements Serializable {
	private static final long serialVersionUID = -635058698980457102L;

	private final Date start, end;

	public Period(Date start, Date end) {
		this.start = new Date(start.getTime());
		this.end = new Date(end.getTime());

		if (this.start.compareTo(this.end) > 0) {
			throw new IllegalArgumentException(start + " after " + end);
		}
	}

	public boolean isValid() {
		return (start.compareTo(end) <= 0);
	}

	@Override
	public String toString() {
		return "Period [start=" + start + ", end=" + end + "]";
	}

	private Object writeReplace() {
		return new SerializationProxy(this);
	}

	private void readObject(ObjectInputStream s) throws InvalidObjectException {
		throw new InvalidObjectException("Proxy required");
	}

	private static class SerializationProxy implements Serializable {
		private static final long serialVersionUID = -2650290278575927672L;

		private final Date start;
		private final Date end;

		public SerializationProxy(Period p) {
			this.start = p.start;
			this.end = p.end;
		}

		private Object readResolve() {
			return new Period(start, end);
		}
	}
}